﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DDBuildTools.DataAccess;
using DDBuildTools.DataAccess.Components;
using System.Diagnostics;

namespace DDBuildTools
{
    /// <summary>
    /// 主程序
    /// </summary>
    public partial class DDBuildTools : Form
    {
        private List<TableEntity> _TableList;
        private string _DataBaseCode;
        /// <summary>
        /// 实始化
        /// </summary>
        public DDBuildTools()
        {
            InitializeComponent();
        }


        private void DDBuildTools_Load(object sender, EventArgs e)
        {
            combDataBaseType.DataSource = new Common().GetDataBaseList();
            combConnection.DataSource = new Common().GetConnList();
            combTemplate.DataSource = new Common().GetTemplateList();
            btGo.Enabled = false;
            lkAll.Enabled = false;
            lkClearAll.Enabled = false;
            tbSavePath.Text = System.AppDomain.CurrentDomain.BaseDirectory + @"BuildDocument\";
            InitConfig();
        }

        private void btGo_Click(object sender, EventArgs e)
        {

            if (combDataBaseType.Text.Trim() + "" == "")
            {
                MessageBox.Show("Please Select DataBase!", "Alert");
                return;
            }

            if (tbSavePath.Text.Trim() + "" == "")
            {
                MessageBox.Show("Please Input Save Path!", "Alert");
                return;
            }

            if (chkTableList.CheckedItems.Count == 0)
            {
                MessageBox.Show("Please Select Table!", "Alert");
                return;
            }

            List<TableEntity> TableList = new List<TableEntity>();
            BuildToTable(TableList);


            IBuildFile IBuild = (IBuildFile)Activator.CreateInstance("DDBuildTools", string.Format("DDBuildTools.{0}", Common.TemplatetypeNameList[this.combTemplate.Text].ToString())).Unwrap();

            bool rBool = IBuild.BuildFile(TableList, _DataBaseCode, this.combTemplate.Text, this.tbSavePath.Text);

            if (rBool)
            {
                MessageBox.Show("Create Document succeed!", "Alert");
                SaveInitConfig();
            }
            else
            {
                MessageBox.Show("Create Document unsuccessfully", "Alert");
            }
        }

        /// <summary>
        /// Remove Table
        /// </summary>
        /// <param name="TableList">List TableEntity</param>
        private void BuildToTable(List<TableEntity> TableList)
        {
            foreach (TableEntity var in _TableList)
            {
                TableList.Add(var);
            }
            List<string> RemoveTable = new List<string>();

            for (int i = 0; i < chkTableList.Items.Count; i++)
            {
                if (!chkTableList.CheckedItems.Contains(chkTableList.Items[i]))
                {
                    RemoveTable.Add(chkTableList.Items[i].ToString());
                }
            }

            for (int i = 0; i < RemoveTable.Count; i++)
            {
                int iIndex = 0;
                foreach (TableEntity var in TableList)
                {
                    if (var.TableCode == RemoveTable[i])
                    {
                        TableList.RemoveAt(iIndex);
                        break;
                    }
                    iIndex++;
                }
            }
        }


        private void btBrowse_Click(object sender, EventArgs e)
        {
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.tbSavePath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void buConnect_Click(object sender, EventArgs e)
        {
            if (this.combConnection.Text.Trim() == "")
            {
                MessageBox.Show("Please Input Connection!", "Alert");
                return;
            }
            string Error = "";
            if (!InitDataTable(out Error))
            {
                MessageBox.Show(Error, "Connection DataBase Error!");
                return;
            }
            BindTableList();
        }



        private bool InitDataTable(out string Error)
        {
            chkTableList.Items.Clear();
            Error = "";
            bool rBool = true;
            try
            {
                _DataBaseCode = "";
                _TableList = new DBHelp().GetDataBaseTable(this.combConnection.Text.Trim(), Common.DataBaseList[this.combDataBaseType.SelectedItem.ToString().Trim()].ToString(), out _DataBaseCode);
            }
            catch (Exception ex)
            {
                Error = ex.ToString();
                rBool = false;
            }
            return rBool;
        }

        private void BindTableList()
        {
            foreach (TableEntity var in _TableList)
            {
                chkTableList.Items.Add(string.Format("{0}", var.TableCode));
            }
            lkAll.Enabled = true;
            lkClearAll.Enabled = true;
            SelectAll();
            btGo.Enabled = true;
        }

        private void lkAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectAll();
        }

        private void SelectAll()
        {
            for (int i = 0; i < chkTableList.Items.Count; i++)
            {
                chkTableList.SetItemChecked(i, true);
            }
        }
        private void ClearAll()
        {
            for (int i = 0; i < chkTableList.Items.Count; i++)
            {
                chkTableList.SetItemChecked(i, false);
            }
        }
        private void lkClearAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ClearAll();
        }

        private void combConnection_SelectedValueChanged(object sender, EventArgs e)
        {
            chkTableList.Items.Clear();
            lkClearAll.Enabled = false;
            lkAll.Enabled = false;
            btGo.Enabled = false;
        }

        private void combDataBaseType_SelectedValueChanged(object sender, EventArgs e)
        {
            chkTableList.Items.Clear();
            lkClearAll.Enabled = false;
            lkAll.Enabled = false;
            btGo.Enabled = false;
            buConnect.Enabled = true;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
            startInfo.Arguments = "www.supesoft.com";
            Process process1 = new Process();
            process1.StartInfo = startInfo;
            process1.Start();
        }

        private void InitConfig()
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(InitPath);
            if (fi.Exists)
            {
                DataSet ds = new DataSet();
                ds.ReadXml(InitPath);
                this.combDataBaseType.Text = ds.Tables["root"].DefaultView[0]["DataBaseType"].ToString();
                this.tbSavePath.Text = ds.Tables["root"].DefaultView[0]["SavePath"].ToString();
                this.combConnection.Text = ds.Tables["root"].DefaultView[0]["Connection"].ToString();
                this.combTemplate.Text = ds.Tables["root"].DefaultView[0]["Template"].ToString();
            }

        }

        private void SaveInitConfig()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<root>");
            sb.AppendFormat("<DataBaseType>{0}</DataBaseType>", combDataBaseType.Text.Trim());
            sb.AppendFormat("<SavePath>{0}</SavePath>", tbSavePath.Text.Trim());
            sb.AppendFormat("<Connection>{0}</Connection>", this.combConnection.Text.Trim());
            sb.AppendFormat("<Template>{0}</Template>", this.combTemplate.Text.Trim());
            sb.Append("</root>");
            Common.WriteFile(sb.ToString(), InitPath);
        }
        private string InitPath
        {
            get
            {
                return System.AppDomain.CurrentDomain.BaseDirectory + "\\InitData.xml";
            }
        }
    }
}